package com.itany.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.itany.cloud.global.GlobalSentinelException;
import com.itany.cloud.util.ResponseResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 石小俊
 */
@RestController
@RequestMapping
public class HelloController {

    // value:指定资源名称,其值不能带有/,如果没有指定资源名称,则直接为空字符串即可
    // blockHandler:指定当前类中的那一个方法用于处理异常,其值是 对应的方法名
    @SentinelResource(value = "f1", blockHandler = "handlerException")
    @RequestMapping("/f1")
    public ResponseResult f1() {
        return ResponseResult.success();
    }

    // 处理自定义异常消息,该方法必须满足几个条件
    // 1.此处的方法返回值类型必须与资源所对应的方法返回值类型一致
    // 2.其方法参数必须与当前方法保持一致,且额外添加一个参数BlockException
    // 3.该方法必须与资源所在的方法处于同一个类中
    // 4.该方法必须通过public修饰
    public ResponseResult handlerException(BlockException e) {
        return ResponseResult.fail("Sentinel异常,异常为:" + e);
    }

    // blockHandlerClass:指定全局异常处理类
    // blockHandler:指定全局异常处理类中的那一个方法用于处理此处异常
    @SentinelResource(value = "f2", blockHandlerClass = GlobalSentinelException.class, blockHandler = "handlerException")
    @RequestMapping("/f2")
    public ResponseResult f2() {
        return ResponseResult.success();
    }

    @RequestMapping("/f3")
    public ResponseResult f3() {
        System.out.println("当前毫秒数:" + System.currentTimeMillis());
        return ResponseResult.success();
    }

    @RequestMapping("/f4/{id}")
    public ResponseResult f4(@PathVariable Integer id) {
        if (id == 1) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        if (id == 2) {
            int i = 1 / 0;
        }
        return ResponseResult.success();
    }

    @SentinelResource(value = "f5",blockHandler = "handlerException5")
    @RequestMapping("/f5")
    public ResponseResult f5(String s1, String s2) {
        return ResponseResult.success("f5执行成功,第一个参数为:" + s1 + ",第二个参数为:" + s2);
    }

    public ResponseResult handlerException5(String s1, String s2,BlockException e) {
        return ResponseResult.fail("Sentinel热点参数限流了");
    }

    @RequestMapping("/f6")
    public ResponseResult f6(){
        return ResponseResult.success("授权规则测试成功");
    }
}
